import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'

// 开发菜单全局状态管理
const showDevMenus = ref(false)
const menuToggles = reactive({
  devTest: true,
  storyDriven: true,
  miaomaTest: true
})

// 从localStorage加载设置
const loadSettings = () => {
  try {
    const saved = localStorage.getItem('dev-menu-settings')
    if (saved) {
      const settings = JSON.parse(saved)
      showDevMenus.value = settings.showDevMenus || false
      Object.assign(menuToggles, {
        devTest: settings.menuToggles?.devTest ?? true,
        storyDriven: settings.menuToggles?.storyDriven ?? true,
        miaomaTest: settings.menuToggles?.miaomaTest ?? true
      })
    }
  } catch (error) {
    console.warn('Failed to load dev menu settings from localStorage:', error)
  }
}

// 保存设置到localStorage
const saveSettings = () => {
  try {
    const settings = {
      showDevMenus: showDevMenus.value,
      menuToggles: { ...menuToggles }
    }
    localStorage.setItem('dev-menu-settings', JSON.stringify(settings))
  } catch (error) {
    console.warn('Failed to save dev menu settings to localStorage:', error)
  }
}

// 初始加载设置
loadSettings()

export const useDevMenus = () => {
  const router = useRouter()

  // 切换开发菜单显示
  const toggleDevMenus = (value?: boolean) => {
    showDevMenus.value = value !== undefined ? value : !showDevMenus.value
    
    if (!showDevMenus.value) {
      // 隐藏开发菜单时，如果当前选中的是开发菜单项，切换到仪表板
      const currentRoute = router.currentRoute.value
      if (currentRoute.path.includes('/development-test') || 
          currentRoute.path.includes('/story-driven') ||
          currentRoute.path.startsWith('/miaoma')) {
        router.push('/dashboard')
      }
    }
    
    saveSettings()
  }

  // 检查当前路由是否为开发菜单相关路由
  const isCurrentRouteDevMenu = () => {
    const currentRoute = router.currentRoute.value
    return currentRoute.path.includes('/development-test') || 
           currentRoute.path.includes('/story-driven') ||
           currentRoute.path.startsWith('/miaoma')
  }

  // 切换特定菜单项
  const toggleMenuItem = (menuKey: keyof typeof menuToggles, value?: boolean) => {
    menuToggles[menuKey] = value !== undefined ? value : !menuToggles[menuKey]
    saveSettings()
  }

  // 重置所有设置
  const resetSettings = () => {
    showDevMenus.value = false
    Object.assign(menuToggles, {
      devTest: true,
      storyDriven: true,
      miaomaTest: true
    })
    saveSettings()
  }

  return {
    // 状态
    showDevMenus,
    menuToggles,
    
    // 方法
    toggleDevMenus,
    toggleMenuItem,
    resetSettings,
    saveSettings,
    loadSettings,
    isCurrentRouteDevMenu
  }
}